<template>
  <cs-card v-loading="loading">
    <div class="formTitle_G">
      <span>广告详情</span>
      <div>
        <cs-btn btnText="取消" type="search" @click.native="onCancel" />
        <template v-if="type === 'edit'">
          <cs-btn
            btnText="预留广告位"
            :type="result.reserved ? 'primary' : 'search'"
            @click.native="changeReserved"
          />
          <cs-btn btnText="保存" type="primary" @click.native="onSave" />
        </template>
      </div>
    </div>
    <div class="formContent_G">
      <el-form
        :model="result"
        :rules="rules"
        label-width="80px"
        class="form_G"
        ref="editFormRef"
      >
        <el-form-item label="广 告 主" prop="owner">
          <el-input
            v-model.trim="result.owner"
            :disabled="type === 'readonly'"
          ></el-input>
        </el-form-item>
        <el-form-item label="广告名称" prop="name">
          <el-input
            v-model.trim="result.name"
            :disabled="type === 'readonly'"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="投放小区"
          prop="communityIds"
          :class="
            residentialAreaLabelData.length === 0 ? '' : 'formItemBottom_6_G'
          "
        >
          <cs-tag
            type="plainPrimary"
            v-for="item in residentialAreaLabelData"
            :key="item.id"
            :isClose="type !== 'readonly'"
            class="communityTag_G"
            @closeTagEvent="closeResidentialFormTagEvent(item.id)"
            >{{ item.label }}
          </cs-tag>
          <cs-tag
            type="plainPrimary"
            :isClose="false"
            v-show="isSelectAllCommunity"
            class="communityTag_G"
            >已选取现有全部小区
          </cs-tag>
          <cs-btn
            v-if="type !== 'readonly'"
            btnText="添加投放小区"
            type="primary"
            @click.native="isShowResidentialAreaDialog = true"
          />
        </el-form-item>
        <el-form-item label="投放类型" prop="sendType">
          <template v-for="item in advertSendType">
            <el-radio
              @change="queryTimeScale"
              :disabled="type === 'readonly'"
              :key="item.id"
              v-model="result.sendType"
              :label="item.value"
              class="formRadio_G"
            >
              {{ item.name }}
            </el-radio>
          </template>
        </el-form-item>
        <el-form-item label="投放时间" prop="time">
          <el-date-picker
            @change="queryTimeScale"
            v-model="result.time"
            :disabled="type === 'readonly'"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="投放位置"
          v-if="result.sendType === '2'"
          class="positionFormItem"
          prop="sendPos"
        >
          <template v-for="item in adSendPos">
            <el-radio
              @change="queryTimeScale"
              :disabled="type === 'readonly'"
              v-model="result.sendPos"
              :label="item.value"
              class="formRadio_G"
              :key="item.id"
              >{{ item.name }}
            </el-radio>
          </template>
        </el-form-item>
        <el-form-item
          label="图片位置"
          v-if="result.sendType === '1'"
          class="positionFormItem"
          prop="imgPos"
        >
          <template v-for="item in advertPosition">
            <el-radio
              @change="queryTimeScale"
              :disabled="type === 'readonly'"
              v-model="result.imgPos"
              :label="item.value"
              class="formRadio_G"
              :key="item.id"
              >{{ item.name }}
            </el-radio>
          </template>
        </el-form-item>
        <el-form-item label="时 间 段" prop="timeScales">
          <div class="timeSlotRadioBox">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkTimeAll"
              @change="handleCheckAllChange"
              :disabled="type === 'readonly'"
              >全选
            </el-checkbox>
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="result.timeScales"
              @change="handleCheckedTimesChange"
            >
              <el-checkbox
                v-for="item in advertTimeScale"
                :label="item.name"
                :disabled="
                  type === 'readonly' ||
                  (!item.usable && checkedCurrent(item.name))
                "
                :key="item.id"
              >
                {{ item.value }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item
          :label="result.sendType === '3' ? '上传图片' : '上传封面'"
          class="formUploadCover_G"
          prop="coverUrl"
        >
          <el-upload
            :disabled="type === 'readonly'"
            class="avatar-uploader_G"
            :action="uploadURL"
            list-type="picture-card"
            :headers="headerObj"
            :limit="1"
            :file-list="result.fileList"
            :on-progress="handleImgUploadProgress"
            :on-success="handleImgSuccess"
            :on-error="handleImgError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadImgRemove"
            :class="result.coverUrl ? 'uploadImg' : ''"
          >
            <i class="el-icon-plus"></i>
            <span class="addPhoto_G" v-show="isShowUploadTip">添加照片</span>
          </el-upload>
          <div class="uploadCoverTipBox_G">
            <div class="uploadCoverTip_G">
              <span>*</span>
              <span>建议banner图封面尺寸674*276px</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="图片缩放"
          v-if="result.sendType === '3'"
          prop="ratioFlag"
        >
          <template v-for="item in advertRatio">
            <el-radio
              :disabled="type === 'readonly'"
              v-model="result.ratioFlag"
              :label="item.value"
              class="formRadio_G"
              :key="item.id"
              >{{ item.name }}
            </el-radio>
          </template>
        </el-form-item>
        <el-form-item
          v-if="result.sendType === '3'"
          label="弹出规则"
          prop="popupRule"
        >
          <el-select
            :disabled="type === 'readonly'"
            v-model="result.popupRule"
            placeholder="请选择"
            clearable
            class="ejectRuleSelect"
          >
            <template v-for="item in adPopupRule">
              <el-option :label="item.name" :value="item.value" :key="item.id">
              </el-option>
            </template>
          </el-select>
          <el-radio
            v-model="result.clicked"
            :disabled="type === 'readonly'"
            :label="1"
            v-if="result.sendType === '3'"
            @click.native.prevent="ejectRadioClick"
            class="formRadio_G"
          >
            用户点击后不在弹出
          </el-radio>
        </el-form-item>
        <el-form-item label="广告内容">
          <div v-if="result.sendType !== '2'">
            <template v-for="item in advertContent">
              <el-radio
                @change="result.content = ''"
                :disabled="type === 'readonly'"
                :key="item.id"
                v-model="result.contentType"
                :label="item.value"
                class="formRadio_G"
              >
                {{ item.name }}
              </el-radio>
            </template>
          </div>
          <div
            id="richTextEditorBox"
            v-show="result.sendType === '2' || result.contentType === '3'"
          ></div>
          <el-input
            :disabled="type === 'readonly'"
            v-show="result.contentType === '2' && result.sendType !== '2'"
            v-model.trim="result.content"
            placeholder="必填，请输入链接"
          ></el-input>
          <el-input
            :disabled="type === 'readonly'"
            v-show="result.contentType === '4' && result.sendType !== '4'"
            v-model.trim="result.content"
            placeholder="请输入内部链接"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="result.coverUrl" alt="" class="previewImg" />
    </el-dialog>
    <!-- 投放小区 -->
    <el-dialog
      title="投放小区"
      :visible.sync="isShowResidentialAreaDialog"
      width="681px"
      class="dialogTitle_G"
      @open="residentialAreaDialogOpen"
      @close="residentialAreaDialogClose"
    >
      <!-- <div>
        <cs-tag
          type="plainPrimary"
          v-for="item in residentialAreaList.list"
          :key="item.communityId"
          :isClick="true"
          :id="item.communityId"
          :clickIds="tempResidentialAreaIdArray"
          @closeTagEvent="closeResidentialAreaDialogTagEvent(item.communityId)"
          @csTagClick="
            residentialAreaDialogCsTagClick(item.communityId, item.name)
          "
          class="newsTypeCsTag"
          >{{ item.name }}
        </cs-tag>
        <cs-btn
          btnText="添加投放小区"
          type="primary"
          @click.native="addResidentialAreaDialogVisible"
        />
      </div>
      <div class="pagination_right_G pagination_right_dialog_G">
        <span class="currentSelect_G currentSelect_dialog_G">{{
          `共${residentialAreaList.totalCount}项`
        }}</span>
        <cs-pagination
          :currentPage="residentialAreaList.currPage"
          :totalPage="residentialAreaList.totalPage"
          @firstPageClick="firstPageClick"
          @previousPageClick="previousPageClick"
          @nextPageClick="nextPageClick"
          @lastPageClick="lastPageClick"
        />
      </div> -->
      <!-- <el-transfer
        v-model="tempResidentialAreaData"
        :data="residentialAreaData"
      >
        <el-button
          class="transfer-footer"
          slot="left-footer"
          size="small"
          @click="loadMoreResidentialArea"
          :loading="loadMoreBtnStatus"
          >加载更多</el-button
        >
        <el-button
          class="transfer-footer"
          slot="left-footer"
          size="small"
          :type="result.selectAllCommunity ? 'primary' : ''"
          @click="selectAllResidentialArea"
          >选取全部小区</el-button
        >
      </el-transfer> -->
      <el-transfer
        :data="residentialAreaData"
        @left-check-change="leftCheckChange"
        ref="transfer"
      >
        <el-button
          class="transfer-footer"
          slot="left-footer"
          size="small"
          @click="loadMoreResidentialArea"
          :loading="loadMoreBtnStatus"
          >加载更多</el-button
        >
        <el-button
          class="transfer-footer"
          slot="left-footer"
          size="small"
          :type="result.selectAllCommunity ? 'primary' : ''"
          @click="selectAllResidentialArea"
          >选取现有全部小区</el-button
        >
      </el-transfer>
      <div class="dialog-footer_G">
        <cs-btn
          type="primary"
          @click.native="selectResidentialAreaBtnClick"
          btnText="确定"
          class="confirmBtn"
        />
        <cs-btn
          @click.native="isShowResidentialAreaDialog = false"
          btnText="取消"
        />
      </div>
    </el-dialog>
  </cs-card>
</template>

<script>
import CsCard from "@/components/CsCard/CsCard.vue";
import CsBtn from "@/components/CsBtn/CsBtn.vue";
import CsTag from "@/components/CsTag/CsTag.vue";
import CsPagination from "@/components/CsPagination/CsPagination.vue";

import E from "wangeditor";
import { queryByType } from "@/api/dictData";
import { queryAdById, queryTimeScale, updateAdvert } from "@/api/ad";
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import { cloneDeep, throttle } from "lodash";

export default {
  name: "AdAdvertise",
  components: {
    CsCard,
    CsBtn,
    CsTag,
    CsPagination,
  },
  props: {
    advertId: {
      require: true,
    },
    type: {
      require: true,
    },
  },
  data() {
    // 选取投放小区自定义校验规则
    const checkCommunity = (rule, value, callback) => {
      if (value.length !== 0) {
        callback();
      } else if (this.isSelectAllCommunity) {
        callback();
      } else if (value.length === 0) {
        return callback(new Error("请选择小区"));
      }
    };

    return {
      loading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      uploadImgList: [],
      isShowUploadTip: true,
      isIndeterminate: true,
      checkTimeAll: false,
      // 广告投放类型
      advertSendType: [],
      // 广告内容类型
      advertContent: [],
      // 时间刻度
      advertTimeScale: [],
      // 图片位置
      advertPosition: [],
      // 图片缩放
      advertRatio: [],
      // 投放位置
      adSendPos: [],
      // 弹出规则
      adPopupRule: [],
      result: {
        owner: "",
        name: "",
        sendType: "",
        contentType: "",
        imgPos: "",
        sendPos: "",
        coverUrl: "",
        ratioFlag: "",
        popupRule: "",
        content: "",
        fromDate: "",
        toDate: "",
        status: "",
        timeScales: [],
        clicked: "",
        communityIds: [],
        time: [],
        reserved: "",
        selectAllCommunity: false,
      },
      // 上传地址
      uploadURL: process.env.VUE_APP_BASE_API + "/sys/fileManager/upload",
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: getToken(),
      },
      previewVisible: false,
      // 投放小区对话框 start
      isShowResidentialAreaDialog: false, // 是否显示投放小区对话框
      // tempResidentialAreaIdArray: [], // 临时投放小区ID数组数据
      // tempResidentialAreaLabelData: [], // 临时投放小区标签数据
      loadMoreBtnStatus: false,
      isSelectAllCommunity: false,
      tempResidentialAreaData: [],
      residentialAreaData: [],
      residentialAreaLabelData: [], // 投放小区标签数据,
      residentialAreaData: [],
      offset: 1,
      limit: 10,
      tempTimeScales: [],
      tempResult: {},
      // 表单验证
      rules: {
        owner: [
          { required: true, message: "请输入广告主名称", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
        communityIds: [
          {
            required: true,
            validator: checkCommunity,
            trigger: "change",
          },
        ],
        sendType: [
          { required: true, message: "请选择投放类型", trigger: "change" },
        ],
        time: [
          {
            type: "array",
            required: true,
            message: "请选择投放时间",
            trigger: "change",
          },
        ],
        sendPos: [
          { required: true, message: "请选择投放位置", trigger: "change" },
        ],
        imgPos: [
          { required: true, message: "请选择图片位置", trigger: "change" },
        ],
        timeScales: [
          {
            type: "array",
            required: true,
            message: "请选择投放时间段",
            trigger: "change",
          },
        ],
        coverUrl: [
          { required: true, message: "请选择上传图片", trigger: "change" },
        ],
        ratioFlag: [
          { required: true, message: "请选择图片缩放", trigger: "change" },
        ],
        popupRule: [
          { required: true, message: "请选择弹出规则", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getResidentialData();
    this.getAdvertSendType();
    this.getAdvertContent();
    this.getAdvertPosition();
    this.getAdvertRatio();
    this.getAdSendPos();
    this.getAdPopupRule();
  },
  async mounted() {
    await this.getDetailById();
    this.createWebRichTextEditor();
  },
  computed: {
    ...mapState("residentialArea", ["residentialAreaList"]),
    filterData() {
      if (this.result.time && this.result.time.length === 2) {
        return {
          ...this.result,
          fromDate: this.result.time[0],
          toDate: this.result.time[1],
        };
      } else {
        return {
          ...this.result,
          fromDate: "",
          toDate: "",
        };
      }
    },
  },
  watch: {
    "result.sendType": function (val, oldVal) {
      if (
        val === this.tempResult.sendType &&
        this.result.imgPos === this.tempResult.imgPos &&
        this.result.sendPos === this.tempResult.sendPos &&
        this.result.time.toString() === this.tempResult.toString()
      ) {
        this.result.timeScales = this.tempTimeScales;
      } else {
        this.result.timeScales = [];
      }
    },
    "result.imgPos": function (val, oldVal) {
      if (
        val === this.tempResult.imgPos &&
        this.result.sendType === this.tempResult.sendType &&
        this.result.sendPos === this.tempResult.sendPos &&
        this.result.time.toString() === this.tempResult.toString()
      ) {
        this.result.timeScales = this.tempTimeScales;
      } else {
        this.result.timeScales = [];
      }
    },
    "result.sendPos": function (val, oldVal) {
      if (
        val === this.tempResult.sendPos &&
        this.result.sendType === this.tempResult.sendType &&
        this.result.imgPos === this.tempResult.imgPos &&
        this.result.time.toString() === this.tempResult.toString()
      ) {
        this.result.timeScales = this.tempTimeScales;
      } else {
        this.result.timeScales = [];
      }
    },
    "result.time": function (val, oldVal) {
      if (
        val.toString() === this.tempResult.time.toString() &&
        this.result.sendType === this.tempResult.sendType &&
        this.result.imgPos === this.tempResult.imgPos &&
        this.result.sendPos === this.tempResult.sendPos
      ) {
        this.result.timeScales = this.tempTimeScales;
      } else {
        this.result.timeScales = [];
      }
    },
    // 'result.toDate': function(val, oldVal) {
    //   if (val === this.tempResult.toDate && this.result.sendType === this.tempResult.sendType && this.result.imgPos === this.tempResult.imgPos && this.result.sendPos === this.tempResult.sendPos && this.result.fromDate === this.tempResult.fromDate) {
    //     this.result.timeScales = this.tempTimeScales
    //   } else {
    //     this.result.timeScales = []
    //   }
    // }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.previewVisible = true;
    },
    handleImgUploadProgress(event, file, fileList) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.isShowUploadTip = false;
    },
    handleImgSuccess(response, file, fileList) {
      if (response.code !== 0) return;
      this.result.coverUrl = response.data.netPath;
      // console.log('response', response)
      // console.log('file', file)
      // console.log('fileList', fileList)
    },
    handleImgError() {
      this.result.coverUrl = "";
      this.isShowUploadTip = true;
      this.$message.error("图片上传失败");
    },
    handleUploadImgRemove() {
      this.result.coverUrl = "";
      this.isShowUploadTip = true;
    },
    // 单选按钮改为复选按钮
    ejectRadioClick() {
      this.result.clicked = this.result.clicked === 1 ? 2 : 1;
    },
    createWebRichTextEditor() {
      const that = this;
      const editor = new E("#richTextEditorBox");
      // 设置编辑器高度
      editor.config.uploadImgServer =
        process.env.VUE_APP_BASE_API + "/sys/fileManager/wangEditorUpload";
      editor.config.uploadVideoServer =
        process.env.VUE_APP_BASE_API + "/sys/fileManager/wangEditorUpload";
      editor.config.uploadImgHeaders = {
        Authorization: getToken(),
      };
      editor.config.uploadVideoHeaders = {
        Authorization: getToken(),
      };
      editor.config.uploadFileName = "file";
      editor.config.uploadVideoAccept = ["mp4", "wmv"];
      editor.config.uploadVideoName = "file";
      editor.config.height = 148;
      editor.config.placeholder = "必填，请输入公告内容";
      editor.config.zIndex = 200;
      // 取消自动 focus
      editor.config.focus = false;
      if (that.result.sendType === "2" || that.result.contentType === "3") {
        editor.config.onchange = function (html) {
          console.log(html);
          // 第二步，监控变化，同步更新到 textarea
          that.result.content = html;
        };
      }

      editor.create();
      // this.$nextTick(() => {
      //   editor.txt.html(this.result.content)
      // })
      // console.log('富文本', that.result.content)
      editor.txt.html(that.result.content);
      if (this.type === "readonly") {
        editor.disable();
      }
    },
    onCancel() {
      this.$router.back();
      // console.log(this.result)
      // console.log('小区标签', this.residentialAreaLabelData)
    },
    // 数字字典数据-
    async getAdvertSendType() {
      // 例如: banner、弹屏等类型的广告
      const { data, code } = await queryByType("advert_send_type");
      if (code !== 0) return;
      this.advertSendType = data;
    },
    async getAdvertContent() {
      // 例如: banner、弹屏等类型的广告
      const { data, code } = await queryByType("advert_content");
      if (code !== 0) return;
      this.advertContent = data;
    },
    async getAdvertTimeScale() {
      // 时间刻度
      const { data, code } = await queryByType("advert_time_scale");
      if (code !== 0) return;
      const filterData = data.map((item) => {
        item.filterValue = item.value.split("-")[0];
        return item;
      });
      this.advertTimeScale = filterData;
    },
    // 图片位置
    async getAdvertPosition() {
      const { data, code } = await queryByType("advert_position");
      if (code !== 0) return;
      this.advertPosition = data;
    },
    async getAdvertRatio() {
      const { data, code } = await queryByType("advert_ratio");
      if (code !== 0) return;
      this.advertRatio = data;
    },
    async getAdSendPos() {
      const { data, code } = await queryByType("ad_send_pos");
      if (code !== 0) return;
      this.adSendPos = data;
    },
    async getAdPopupRule() {
      const { data, code } = await queryByType("ad_popup_rule");
      if (code !== 0) return;
      this.adPopupRule = data;
    },
    async getDetailById() {
      this.loading = true;
      const { data, code, msg } = await queryAdById({
        advertId: this.advertId,
      });
      if (code !== 0) return this.$message.error(msg);
      this.result.owner = data.owner;
      this.result.name = data.name;
      this.result.sendType = data.sendType === null ? "" : data.sendType.value;
      this.result.contentType =
        data.contentType === null ? "" : data.contentType.value;
      this.result.imgPos = data.imgPos === null ? "" : data.imgPos.value;
      this.result.sendPos = data.sendPos === null ? "" : data.sendPos.value;
      this.result.ratioFlag =
        data.ratioFlag === null ? "" : data.ratioFlag.value;
      this.result.popupRule =
        data.popupRule === null ? "" : data.popupRule.value;
      this.result.coverUrl = data.coverUrl;
      this.result.content = data.content;
      this.result.fromDate = data.fromDate;
      this.result.toDate = data.toDate;
      this.result.status = data.status;
      this.result.timeScales =
        data.timeScales === null ? [] : [...data.timeScales];
      this.result.clicked = data.clicked;
      this.result.communityIds = data.community.map((item) => item.communityId);
      this.result.time = [data.fromDate, data.toDate];
      this.result.reserved = data.reserved;
      this.result.fileList = [{ url: data.coverUrl }];
      this.result.community = [...data.community];
      this.tempTimeScales =
        data.timeScales === null ? [] : [...data.timeScales];
      this.residentialAreaLabelData = data.community.map((item) => {
        return {
          id: item.communityId,
          label: item.name,
        };
      });
      this.tempResult = cloneDeep(this.result);
      console.log("详情结果", data);
      await this.queryTimeScale();
    },
    // 查询时间粒度
    async queryTimeScale() {
      this.loading = true;
      const { data, code, msg } = await queryTimeScale({
        fromDate: this.filterData.fromDate,
        toDate: this.filterData.toDate,
        sendType: this.filterData.sendType,
        imgPos: this.filterData.imgPos,
        sendPos: this.filterData.sendPos,
      });
      this.advertTimeScale = data;
      // if (code !== 0) return this.$message.error(msg)
      // const filterData = data.map(item => {
      //   item.filterValue = item.value.split('-')[0]
      //   return item
      // })
      // this.advertTimeScale = filterData
      console.log("时间粒度", data);
      this.loading = false;
    },
    // 投放小区对话框相关事件 start------------------------
    // 投放小区对话框打开事件
    // 获取小区列表
    async getResidentialData() {
      await this.$store.dispatch("residentialArea/getResidentialAreaList", {
        offset: this.offset,
        limit: this.limit,
      });
      this.residentialAreaList.list.forEach((item) => {
        this.residentialAreaData.push({
          key: item.communityId,
          label: item.name,
          disabled: false,
        });
      });
    },
    residentialAreaDialogOpen() {
      // 对数据进行浅拷贝
      // this.tempResidentialAreaIdArray = JSON.parse(
      //   JSON.stringify(this.result.communityIds)
      // );
      // this.tempResidentialAreaLabelData = JSON.parse(
      //   JSON.stringify(this.residentialAreaLabelData)
      // );

      // this.tempResidentialAreaData = this.residentialAreaLabelData.map(
      //   (item) => item.id
      // );

      this.$nextTick(() => {
        document.querySelectorAll(".el-transfer-panel")[1].style.display =
          "none";

        if (!this.$refs.transfer) return;
        this.$refs.transfer.$refs.leftPanel.checked =
          this.residentialAreaLabelData.map((item) => item.id);
        console.log(this.$refs.transfer.$refs.leftPanel.checked);
      });
    },
    // 投放小区对话框关闭事件
    residentialAreaDialogClose() {
      this.$refs.transfer.$refs.leftPanel.checked = [];
      this.isShowResidentialAreaDialog = false;
    },
    // // 关闭投放小区对话框标签事件
    // closeResidentialAreaDialogTagEvent(id) {
    //   // console.log('关闭投放小区对话框-----', id)
    // },
    // // 投放小区对话框标签点击事件
    // residentialAreaDialogCsTagClick(id, label) {
    //   // 如临时投放小区数组存在点击过的投放小区id，则删除重复id
    //   if (this.tempResidentialAreaIdArray.indexOf(id) !== -1) {
    //     const idPosition = this.tempResidentialAreaIdArray.indexOf(id);
    //     this.tempResidentialAreaIdArray.splice(idPosition, 1);
    //     this.tempResidentialAreaLabelData.splice(idPosition, 1);
    //   } else {
    //     this.tempResidentialAreaIdArray.push(id);
    //     this.tempResidentialAreaLabelData.push({
    //       id,
    //       label,
    //     });
    //   }
    // },
    // // 添加投放小区对话框显示
    // addResidentialAreaDialogVisible() {
    //   // console.log('显示添加投放小区对话框')
    // },
    // 选择投放小区到表单按钮点击事件
    selectResidentialAreaBtnClick() {
      // this.result.communityIds = this.tempResidentialAreaIdArray;
      // this.residentialAreaLabelData = this.tempResidentialAreaLabelData;
      // this.isShowResidentialAreaDialog = false;
      this.residentialAreaLabelData = [];
      this.result.communityIds = this.tempResidentialAreaData;
      this.residentialAreaData.forEach((item) => {
        if (this.tempResidentialAreaData.indexOf(item.key) !== -1) {
          this.residentialAreaLabelData.push({
            id: item.key,
            label: item.label,
          });
        }
      });
      this.isShowResidentialAreaDialog = false;
    },
    leftCheckChange(arr) {
      this.tempResidentialAreaData = arr;
    },
    // firstPageClick() {
    //   this.offset = 1;
    //   this.getResidentialData();
    // },
    // previousPageClick() {
    //   this.offset = this.residentialAreaList.currPage - 1;
    //   this.getResidentialData();
    // },
    // nextPageClick() {
    //   this.offset = this.residentialAreaList.currPage + 1;
    //   this.getResidentialData();
    // },
    // lastPageClick() {
    //   this.offset = this.residentialAreaList.totalPage;
    //   this.getResidentialData();
    // },
    // 关闭表单投放小区标签
    closeResidentialFormTagEvent(id) {
      this.residentialAreaLabelData.forEach((item, index) => {
        if (item.id === id) {
          this.result.communityIds.splice(index, 1);
          this.residentialAreaLabelData.splice(index, 1);
        }
      });
    },
    // 加载更多小区信息
    loadMoreResidentialArea: throttle(async function () {
      this.loadMoreBtnStatus = true;
      if (this.offset === this.residentialAreaList.totalPage) {
        this.$message({
          message: "没有更多了",
          type: "warning",
        });
        this.loadMoreBtnStatus = false;
        return;
      }
      this.offset += 1;
      await this.getResidentialData();
      if (this.result.selectAllCommunity) {
        this.result.selectAllCommunity = false;
        this.isSelectAllCommunity = false;
        this.residentialAreaData = this.residentialAreaData.map((item) => {
          return { key: item.key, label: item.label, disabled: false };
        });
        this.selectAllResidentialArea();
      }
      this.$refs.transfer.$refs.leftPanel.checked =
        this.residentialAreaLabelData.map((item) => item.id);
      this.loadMoreBtnStatus = false;
    }, 500),
    // 选取全部小区
    selectAllResidentialArea() {
      this.result.selectAllCommunity = !this.result.selectAllCommunity;
      this.isSelectAllCommunity = !this.isSelectAllCommunity;
      this.residentialAreaData = this.residentialAreaData.map((item) => {
        return { key: item.key, label: item.label, disabled: !item.disabled };
      });
      if (this.isSelectAllCommunity)
        this.$refs.transfer.$refs.leftPanel.checked = [];
    },
    changeReserved() {
      this.result.reserved = this.result.reserved ? 0 : 1;
    },
    onSave() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const temp = {};
          // console.log('结果', this.result)
          // console.log('对吧', this.tempResult)
          for (const key in this.filterData) {
            if (this.filterData[key] !== this.tempResult[key]) {
              if (this.filterData[key] instanceof Array) {
                if (
                  this.tempResult[key].toString() !==
                  this.filterData[key].toString()
                ) {
                  console.log();
                  temp[key] = this.filterData[key];
                }
              } else {
                temp[key] = this.filterData[key];
              }
            }
          }
          console.log("提交", { ...temp, id: this.advertId });
          const { data, code, msg } = await updateAdvert({
            ...temp,
            id: this.advertId,
          });
          if (code !== 0) return this.$message.error(msg);
          console.log(data, code, msg);
          this.$message.success("添加成功");
          this.loading = false;
          this.$router.push("/advert");
        }
      });
    },
    checkedCurrent(item) {
      if (
        this.result.sendType === this.tempResult.sendType &&
        this.result.imgPos === this.tempResult.imgPos &&
        this.result.sendPos === this.tempResult.sendPos &&
        this.filterData.fromDate === this.tempResult.fromDate &&
        this.filterData.toDate === this.tempResult.toDate
      ) {
        if (this.tempTimeScales.includes(item)) {
          return false;
        } else {
          return true;
        }
      } else {
        return true;
      }
    },
    handleCheckAllChange(val) {
      const allTime = this.advertTimeScale.map((item) => {
        if (item.usable) {
          return item.value.split("-")[0];
        }
      });
      console.log(allTime);
      this.result.timeScales = val ? allTime : [];
      this.isIndeterminate = false;
    },
    handleCheckedTimesChange(value) {
      const checkedCount = value.length;
      this.checkTimeAll = checkedCount === this.result.timeScales.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.advertTimeScale.length;
    },
  },
};
</script>

<style lang="scss" scoped>
.cs-card {
  margin: 26px;
}

.form_G {
  .positionFormItem {
    margin-bottom: 10px;
  }

  .ejectRuleSelect {
    width: 100%;
  }

  .uploadImg {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }
}

.timeSlotRadioBox {
  width: 780px;

  .formRadio_G {
    margin-top: 16px;
  }
}

// 新闻类型对话框样式 start
.newsTypeCsTag {
  margin-right: 29px;
  margin-bottom: 35px;
}

.confirmBtn {
  margin-top: 11px;
}

.el-transfer {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;

  ::v-deep .el-transfer-panel {
    width: 350px;
  }

  ::v-deep .el-transfer-panel__list {
    padding-bottom: 39px;
  }

  ::v-deep .el-transfer__buttons {
    display: none;
  }
}

.previewImg {
  width: 100%;
}

// 新闻类型对话框样式 end
</style>
